package com.atguigu.gmallrealtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.gmallrealtime.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.gmallrealtime.common.Constant;
import com.atguigu.gmallrealtime.util.DateFormatUtil;
import com.atguigu.gmallrealtime.util.DorisUtil;
import com.atguigu.gmallrealtime.util.MyKafkaUtil;
import org.apache.doris.flink.sink.DorisSink;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.stream.Stream;

/**
 * @author yhm
 * @create 2023-10-09 14:06
 */
public class DwsTrafficHomeDetailPageViewWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 创建flink环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 2 添加检查点和状态后端
        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);

        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消之后 检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        // env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));

        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");

        System.setProperty("HADOOP_USER_NAME","atguigu");

        // TODO 3 读取dwd_traffic_page主题数据
        String groupId = "dws_traffic_home_detail_page_view_window";
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(Constant.TOPIC_DWD_TRAFFIC_PAGE, groupId);
        DataStreamSource<String> pageSource = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "page_source");

        // TODO 4 过滤出home和detail页面数据  同时转换为jsonObject
        SingleOutputStreamOperator<JSONObject> jsonStream = pageSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    String pageId = jsonObject.getJSONObject("page").getString("page_id");
                    if ("home".equals(pageId) || "good_detail".equals(pageId)) {
                        out.collect(jsonObject);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        // TODO 5 添加水位线
        SingleOutputStreamOperator<JSONObject> withWaterMarkStream = jsonStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forMonotonousTimestamps().withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("ts");
            }
        }));

        // TODO 6 根据mid分组
        KeyedStream<JSONObject, String> keyedStream = withWaterMarkStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getJSONObject("common").getString("mid");
            }
        });

        // TODO 7 转换结构为javaBean 添加对应的独立访客数
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = keyedStream.map(new RichMapFunction<JSONObject, TrafficHomeDetailPageViewBean>() {

            ValueState<String> homeLastDtState = null;
            ValueState<String> detailLastDtState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> homeLastDtDes = new ValueStateDescriptor<>("home_last_dt", String.class);
                homeLastDtDes.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1L)).build());
                homeLastDtState = getRuntimeContext().getState(homeLastDtDes);

                ValueStateDescriptor<String> detailLastDtDes = new ValueStateDescriptor<>("detail_last_dt", String.class);
                detailLastDtDes.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1L)).build());
                detailLastDtState = getRuntimeContext().getState(detailLastDtDes);
            }

            @Override
            public TrafficHomeDetailPageViewBean map(JSONObject value) throws Exception {
                Long ts = value.getLong("ts");
                String curDt = DateFormatUtil.toDate(ts);
                String dorisDate = DateFormatUtil.toDorisDate(ts);

                String pageId = value.getJSONObject("page").getString("page_id");
                // 首页独立访客数
                Long homeUvCt = 0L;
                // 商品详情页独立访客数
                Long goodDetailUvCt = 0L;
                if ("home".equals(pageId)) {
                    // 当前是首页
                    String homeLastDt = homeLastDtState.value();
                    if (homeLastDt == null || !homeLastDt.equals(curDt)) {
                        // 当前为独立访客
                        homeUvCt = 1L;
                        homeLastDtState.update(curDt);
                    }
                } else {
                    // 当前为详情页
                    String detailLastDt = detailLastDtState.value();
                    if (detailLastDt == null || !detailLastDt.equals(curDt)) {
                        goodDetailUvCt = 1L;
                        detailLastDtState.update(curDt);
                    }
                }
                return new TrafficHomeDetailPageViewBean("", "", dorisDate, homeUvCt, goodDetailUvCt, ts);
            }
        });

//        beanStream.print();

        // TODO 8 开窗聚合
        // 不需要对任何维度进行分组聚合  所以使用windowAll
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> reduceStream = beanStream.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10L))).allowedLateness(org.apache.flink.streaming.api.windowing.time.Time.seconds(5L))
                .reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1, TrafficHomeDetailPageViewBean value2) throws Exception {
                        value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                        value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                        return value1;
                    }
                }, new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context context, Iterable<TrafficHomeDetailPageViewBean> elements, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TimeWindow window = context.window();
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());
                        for (TrafficHomeDetailPageViewBean element : elements) {
                            element.setStt(stt);
                            element.setEdt(edt);
                            out.collect(element);
                        }
                    }
                });

//        reduceStream.print();


        // TODO 9 写出到doris
        reduceStream.map(new MapFunction<TrafficHomeDetailPageViewBean, String>() {
            @Override
            public String map(TrafficHomeDetailPageViewBean value) throws Exception {
                SerializeConfig config = new SerializeConfig();
                config.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
                return  JSON.toJSONString(value, config);
            }
        }).sinkTo(DorisUtil.getDorisSink("dws_traffic_home_detail_page_view_window"));

        // TODO 10 执行任务
        env.execute();

    }
}
